package com.test.realcityalfa.frmwrk;

import java.io.File;
import java.io.FileOutputStream;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import com.test.realcityalfa.CommercialActivity;
import com.test.realcityalfa.Constants;
import com.test.realcityalfa.DashboardActivity;
import com.test.realcityalfa.R;
import com.test.realcityalfa.activityswitchers.ActivitySwitch;
import com.test.realcityalfa.connection.InternetConnection;
import com.test.realcityalfa.connection.RequestMethodFactory;
import com.test.realcityalfa.exception.InternetConnectionException;
import com.test.realcityalfa.exception.NoInternetConnectionException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class CommercialDownloaderAsyncTask extends CustomAsyncTask
{
	String url;
	Activity _activity;
	Context _context;
	File cacheDir;
	ActivitySwitch activitySwitch;
	InternetConnection internetConnection;
	
	
	public CommercialDownloaderAsyncTask(Activity activity,ProgressBar progressBar,String url)
	{
		super(activity.getApplicationContext(), progressBar);
		_activity = activity;
		this.url = url;
		internetConnection = new InternetConnection(RequestMethodFactory.GET_METHOD);
	}
	
	public CommercialDownloaderAsyncTask(Context context, ProgressBar progressBar) 
	{
		super(context, progressBar);
		this._context = context;
	}
	
	@Override
	protected Object asyncOperation() throws Throwable 
	{
		try
		{
			internetConnection.isConnectionAvailable(this._activity);
			publishProgress(doDownload());
			return null;//doDownload();
		}
		catch(NoInternetConnectionException ex)
		{
			return null;
		}
		catch(Exception ex)
		{
			publishProgress(null);
			throw ex;
		}
				
	}

	@Override
	protected void onResult(Object result) throws Exception {
		// TODO Auto-generated method stub
		/*
		activitySwitch = new ActivitySwitch(DashboardActivity.class);
		try
		{
			Object[] object = (Object[]) result;		
			
			activitySwitch.goToNextActivity(this._activity, Constants.Commercial.COMMERCIAL_SHOW_TIME);
		}
		catch(NullPointerException ex)
		{
			activitySwitch.goToNextActivity(this._activity, 0);
		}
		*/
		/*
		activitySwitch.goToNextActivity(this._activity, 3000);
		_activity.startActivity(new Intent(_activity.getApplicationContext(), CommercialActivity.class));
		_activity.finish();
		*/
	}

	@Override
	protected void onProgress(Object update) throws Exception 
	{
		activitySwitch = new ActivitySwitch(DashboardActivity.class);
		try
		{
			Object[] object = (Object[]) update;
			ImageView img = (ImageView) this._activity.findViewById(R.id.commercialImage);
			img.setImageBitmap((Bitmap) object[0]);
			activitySwitch.goToNextActivity(this._activity, Constants.Commercial.COMMERCIAL_SHOW_TIME);
		}
		catch(NullPointerException ex)
		{
			activitySwitch.goToNextActivity(this._activity, 0);
		}
		
		
		
	}
		
	@Override
	protected void onCancelled() 
	{	
		
	}

	public void cancelTask()
	{
		Log.d(getClass().getName(), getClass().getName() + " trying to cancel");
		
		this.activitySwitch.cancelSwitching();
		this.cancel(true);
	}
	
	private Object doDownload()
	{
		if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
		{
			File sdDir = android.os.Environment.getExternalStorageDirectory();
			this.cacheDir = new File(sdDir, "data/realcity/");
			//cacheDir.mkdir();//test
		}
		else
		{
			cacheDir = _context.getCacheDir();
		}
		cacheDir = _activity.getApplicationContext().getCacheDir();
		Log.d("DrawableManager", "Cache directory: " + cacheDir);
		if(!cacheDir.exists())
		{
			cacheDir.mkdir();
		}
		
		
		//test image url http://media.realcity.cz/get_image.php?id=9604252&key=ad
			String filename = String.valueOf(url.hashCode());
			File f = new File(cacheDir, filename);
			
			//if image exists in cache
			Bitmap bmp = BitmapFactory.decodeFile(f.getPath());
			if(bmp != null){return bmp;}		
			
			try
			{
				//set ups the connection
				URLConnection urlConnection = new URL(url).openConnection();
				urlConnection.setConnectTimeout(Constants.InternetConnection.CONNECTION_TIMEOUT);
				urlConnection.setReadTimeout(Constants.InternetConnection.CONNECTION_READ_TIMEOUT);
				
				bmp = BitmapFactory.decodeStream(urlConnection.getInputStream());
				writeFile(bmp, f);
				//Looper.prepare();
				//handleLoadingFinished("done");
				return bmp;
			}
			catch(SocketTimeoutException e)
			{
				//handleConnectionTimeout(e);
				return null;
			}
			catch(Exception e)
			{
				e.printStackTrace();
				return null;
			}	
	}
	
	private void writeFile(Bitmap bmp, File f)
	{
		FileOutputStream out = null;
		
		try
		{
			out = new FileOutputStream(f);
			bmp.compress(Bitmap.CompressFormat.JPEG, 80, out);
		}
		catch(Exception e)
		{e.printStackTrace();}
		finally
		{
			try
			{
				if(out != null){out.close();}
			}
			catch(Exception e)
			{e.printStackTrace();}
		}
		
		
	}
	
	public void setUrl(String url)
	{
		this.url = url;
	}
	
	
	

}


